#! /usr/bin/env python3

import time

from openpyxl import load_workbook

from key_words import KeyWords


# 测试用例表说明
CASE_ID = 1
SHEET_NAME = 4
FLAG = 5
RUN_TIME = 6
CASE_RESULT = 7

# 对应步骤表的字段说明（第1列索引为0）
STEP_DESC = 2
FUNC = 3
BY = 4
EXPR = 5
DATA = 6
TIME = 7
RESULT = 8
IMG = 9
ERROR = 10
   
# 实例化关键字类
kw = KeyWords()
# 加载数据表
wb = load_workbook('testcase.xlsx')
sh = wb['测试用例']
print(f"\n{sh.cell(1,1).value}\n")
sh.cell(1,1).value = '编号'
print(f"\n{sh.cell(1,1).value}\n")
  

def clear_table_data(tableName: str, columns: str = "HIJK"):
    """清除表格中的测试结果"""
    sheet = wb[tableName]
    for col in columns:
        for cell in sheet[col][1:]:
            cell.value = None


clear_table_data('测试用例', 'GH')
for sheet in wb.sheetnames[1:]:
    clear_table_data(sheet)

for case in list(sh.rows)[1:]:
    results = set()
    # 获取测试用例所依赖的表格文件（详细操作步骤）
    sheet_name = wb[case[SHEET_NAME].value]
    # 判断是否执行
    if case[FLAG].value == 'Y':
        for row in list(sheet_name.rows)[1:]:
            # 获取对应操作方法名
            func = row[FUNC].value
            # 获取操作方法所需参数
            args = [row[i].value for i in range(BY, TIME) if row[i].value]
            try:
                # 通过映射调用关键字类中的实例方法
                getattr(kw, func)(*args)
                # 无异常抛出说明测试通过
                row[RESULT].value = "pass"
                results.add('pass')
            except Exception as e:
                # 抛出异常，进行捕获，并标记失败
                row[RESULT].value = "fail"
                results.add('fail')
                row[ERROR].value = f"{type(e)} {str(e)}"
                # 对异常页面进行截图
                row[IMG].value = kw.save_screenshot()
                # 有异常，跳出循环体
                break
            # 刷新时间戳与截图信息 
            finally:
                row[TIME].value = kw.now_time() 
        # 正常通过后进行截图（异常情况直接跳出循环）
        row[IMG].value = kw.save_screenshot()
        # 用例表中填写执行时间与测试结论
        case[RUN_TIME].value = kw.now_time()
        if 'fail' in results:
            case[CASE_RESULT].value = 'fail'
        else:
            case[CASE_RESULT].value = 'pass'
        # 关闭浏览器
        kw.quit()
    # 跳过测试用例                
    else:
        case[RUN_TIME].value = '/'
        case[CASE_RESULT].value = '/'
wb.save('/Users/maxiao/PythonProject/testcase.xlsx')


